<template>
    <div id="wechat-member-list-mescroll" :style="{height: `${height}px`}">
        <div 
        class="list"
        v-for="item in optListData"
        :key="item.id"
        v-show="item.id === actOpt"
        :id="item.id"
        >
            <ul class="list-ul">
                <li 
                class="list-li"
                v-for="(itemLi, index) in item.list"
                @click.stop="toUser(itemLi.userId, itemLi.thumbSty.tag)"
                :key="index"
                >
                    <div class="head list-li-box">
                        <div class="thumb">
                            <div :class="itemLi.thumbSty.thumbClass" class="thumb-box">
                                <user-head-img 
                                :userImg="itemLi.headImg"
                                :height="itemLi.thumbSty.height"
                                :width="itemLi.thumbSty.width"
                                class="thumb-box-img"
                                @click.stop
                                ></user-head-img>
                                <span>{{itemLi.thumbSty.thumbText}}</span>
                            </div>
                        </div>
                        <div class="content-box">
                            <div v-if="itemLi.nickName" class="wechat-name content-box-row">{{itemLi.nickName}}</div>
                            <div v-if="itemLi.roomNickName" class="member-name content-box-row">{{itemLi.roomNickName}}</div>
                            <div class="wechat-icon content-box-row">
                                <sex-icon class="icon" :top="2" :sex="itemLi.sex"></sex-icon>
                                <span v-if="itemLi.demandText.length > 0" class="opt-tag icon">有需求</span>
                                <span v-if="itemLi.isPartner" class="opt-tag icon">互助</span>
                                <span v-if="itemLi.groupWechat" class="opt-tag icon">微信群</span>
                                <span v-if="itemLi.seminar && itemLi.seminarWorking" class="woshop-working icon">主讲中</span>
                                <span v-else-if="itemLi.seminar" class="opt-tag icon">主讲</span>
                            </div>
                        </div>
                    </div>
                    <div class="opt-list">
                        <user-info-option :selectionId="item.id" :optName="'签名'" :optId="'signature'" :optVal="itemLi.signature"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'位置'" :optId="'area'" :optVal="itemLi.area"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'企业'" :optId="'company'" :optVal="itemLi.company"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'介绍'" :optId="'yourSelf'" :optVal="itemLi.yourSelf"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'供应'" :optId="'supply'" :optVal="itemLi.supply"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'需求'" :optId="'demand'" :optVal="itemLi.demand"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'我找'" :optId="'find'" :optVal="itemLi.findWho"></user-info-option>
                        <user-info-option :selectionId="item.id" :optName="'我帮'" :optId="'myHelp'" :optVal="itemLi.myHelp"></user-info-option>
                    </div>
                    <div v-if="['stick', 'bus'].indexOf(itemLi.thumbSty.tag) > -1" class="statistics">
                        {{itemLi.updateTimeText}}更新 | <image-vant class="visit-count-icon" :src="visitBusIcon" :width="15" :height="15" /> {{itemLi.viewCount}}
                    </div>
                </li>
            </ul>
            <div :id="`${item.id}-empty`" class="empty-info"></div>
        </div>
    </div>
</template>

<script>
// 自定义方法
import { getProImg } from "_projectFn/images"
import { commonRequestData } from '_network/request'
import { failTextVantToa } from "_projectFn/prompt"
import { isLoginChose } from "_projectFn/login"
import { enterUserBus, enterUserIndex, } from "_projectFn/page"
import { checkArrIndexObj } from "_commonFn/array"
import { checkCacheaIsPageData } from "_projectFn/check"
import { getText } from "_commonFn/string"

// 自定义组件
import UserHeadImg from '_components/project/common/UserHeadImg'
import SexIcon from '_components/project/common/SexIcon'
import UserInfoOption from '_components/project/MembelListWechat/UserInfoOption'
import ImageVant from '_components/project/common/ImageVant'

// 本地图片
import scrollTop from '_assets/img/mescroll-totop.png'
import manSexIcon from '_assets/img/sex-man-icon.svg'
import womenSexIcon from '_assets/img/sex-women-icon.svg'
import emptyContentImg from '_assets/img/empty-content-img.svg'
import visitBusImg from '_assets/img/visit-mro-icon.svg'

// 引入mescroll.min.js和mescroll.min.css
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'

export default {
    name: 'List',
    props: {
        optList: { // 选项列表
            type: Array,
            default: []
        },
        actOpt: { // 默认选项
            type: String,
            default: ''
        },
        height: {
            type: Number,
            default: 500,
        },
        query: {
            type: Object,
            default: {},
        },
        defaultOpt: { // 默认选项
            type: String,
            default: 'member'
        },
    },
    data() {
        return {
            mescroll: {
                member: null,
                demand: null,
                help: null,
            },
            mesConfig: {
                member: {
                    total: 0,
                },
                demand: {
                    total: 0,
                },
                help: {
                    total: 0,
                },
            },
            mesCacheConfig: {
                member: {},
                demand: {},
                help: {},
            },
            scrollTopIcon: getProImg('mescroll-totop.png', scrollTop),
            sexImg: {
                man: getProImg("sex-man-icon.svg", manSexIcon),
                women: getProImg("sex-women-icon.svg", womenSexIcon),
            },
            emptyContentIcon: getProImg("sex-women-icon.svg", emptyContentImg),
            visitBusIcon: getProImg("visit-mro-icon.svg", visitBusImg),
        }
    },
    methods: {
        // 群员下拉重新加载
		memberDownCallback() {
            const that = this
			this.downCallback({
                callback() {
                    that.mescroll['member'].endErr()
                }
            })
		},
        // 需求下拉重新加载
		demandDownCallback() {
            const that = this
			this.downCallback({
                callback() {
                    that.mescroll['demand'].endErr()
                }
            })
		},
        // 互助下拉重新加载
		helpDownCallback() {
            const that = this
			this.downCallback({
                callback() {
                    that.mescroll['help'].endErr()
                }
            })
		},
		// 群员上拉加载更多
		memberUpCallback(page) {
            const that = this
            this.upCallback({
                callback() {
                    that.getMemberList(page)
                }
            })
        },
		// 需求上拉加载更多
		demandUpCallback(page) {
            const that = this
            this.upCallback({
                callback() {
                    that.getDemandList(page)
                }
            })
        },
		// 互助上拉加载更多
		helpUpCallback(page) {
            const that = this
            this.upCallback({
                callback() {
                    that.getHelpList(page)
                }
            })
        },
        upCallback({callback}) {
            typeof callback === 'function' && callback(true)
        },
        downCallback({callback}) {
            setTimeout(() => {
                typeof callback === 'function' && callback(true)
			}, 300)
        },
        // 判断返回上拉加载函数
        setUpLoadFn(id) {
            switch (id) {
                case 'member':
                    return this.memberUpCallback
                    break;
                case 'demand':
                    return this.demandUpCallback
                    break;
                case 'help':
                    return this.helpUpCallback
                    break;
                default:
                    return this.memberUpCallback
                    break;
            }
        },
        // 判断返回下拉加载函数
        setDownLoadFn(id) {
            switch (id) {
                case 'member':
                    return this.memberDownCallback
                    break;
                case 'demand':
                    return this.demandDownCallback
                    break;
                case 'help':
                    return this.helpDownCallback
                    break;
                default:
                    return this.memberDownCallback
                    break;
            }
        },
        // 设置加载列表
        setMescrollList() {
            const that = this
            checkCacheaIsPageData({
                sessionStorageKey: 'MemberListWechatCache',
                pageQueryStr: this.$route.query,
                callback() {
                    setTimeout(() => {
                        // console.log('setMescrollList')
                        that.optList.forEach((item, index) => {
                            const upCallback = that.setUpLoadFn(item.id)
                            const downCallback = that.setDownLoadFn(item.id)
                            const upConfig = that.mesCacheConfig[item.id].optUp || {
                                page: {
                                    num: 0,
                                    size: 20
                                },
                                isUpLoadContinue: true,
                                id: item.id
                            }
                            // console.log('upConfig', upConfig)
                            // 在mounted生命周期初始化mescroll,以确保您配置的dom元素能够被找到.
                            that.mescroll[item.id] = new MeScroll(item.id, {
                                down: {
                                    auto: false, // 是否在初始化完毕之后自动执行下拉回调callback; 默认true
                                    callback: downCallback, // 下拉刷新的回调 
                                },
                                up: {
                                    auto: that.actOpt === item.id && that.selectListObj[item.id] && that.selectListObj[item.id].length === 0, // 是否在初始化时以上拉加载的方式自动加载第一页数据; 默认false
                                    callback: upCallback, // 上拉回调,此处可简写; 相当于 callback: function (page) { upCallback(page); }
                                    page: {
                                        num: upConfig.page.num, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
                                        size: upConfig.page.size // 每页数据的数量
                                    },
                                    noMoreSize: 1, // 如果列表已无数据,可设置列表的总数量要大于等于5条才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
                                    isLock: !upConfig.isUpLoadContinue,
                                    toTop: { // 配置回到顶部按钮
                                        src: that.scrollTopIcon
                                    },
                                    htmlNodata: '<div class="is-all-data">已显示全部</div>',
                                    warpClass: 'mescroll-upwarp',
                                    empty: {
                                        //列表第一页无任何数据时,显示的空提示布局; 需配置warpId才显示
                                        warpId:	`${item.id}-empty`, //父布局的id (1.3.5版本支持传入dom元素)
                                        icon: that.emptyContentIcon, //图标,默认null,支持网络图
                                        tip: "没有相关信息内容" //提示
                                    },
                                }
                            })
                            if (upConfig.isUpLoadContinue === false) {
                                if (that.selectListObj[item.id].length > 0) {
                                    that.mescroll[item.id].showNoMore()
                                } else {
                                    that.mescroll[item.id].showEmpty()
                                }
                            }
                        })
                    }, 1)
                }
            })
        },
        // 获取群成员列表
        getMemberList(page) {
            // console.log('获取上拉配置', this.mescroll['member'].optUp)
            commonRequestData({
                apiName: `WxGroupUserItem`,
                requestData: {
                    GroupWxId: this.queryStr.wecGroId,
                    KfWxId: this.queryStr.serWecId,
                    flag: 0,
                    Page: page.num,
                    PageSize: page.size,
                }
            })
            .then(res => {
                console.log("获取微信群成员 res：", res)
                if (res.errcode == 0) {
                    if (this.defaultOpt === 'member') {
                        this.setPageBasicData(res.data)
                    }
                    if (Array.isArray(res.data.UsersItem) && res.data.UsersItem.length > 0) {
                        this.$emit('addList', { // 设置群成员列表数据
                            id: 'member',
                            list: res.data.UsersItem
                        })
                        this.mescroll['member'].endBySize(res.data.UsersItem.length, res.total)
                    } else {
                        const list = checkArrIndexObj({
                            arr: this.optList,
                            key: 'id',
                            val: 'member'
                        }).list
                        this.mescroll['member'].endErr()
                        if (list.length === 0) {
                            this.mescroll['member'].showEmpty()
                        }
                    }
                    this.mesConfig['member'].total = res.total
                } else {
                    if (res.errcode == 1003) {
                        this.$emit('hideDom')
                        return
                    }
                    const list = checkArrIndexObj({
                        arr: this.optList,
                        key: 'id',
                        val: 'member'
                    }).list
                    this.mescroll['member'].endErr()
                    if (list.length === 0) {
                        this.mescroll['member'].showEmpty()
                    }
                }
            }, res => {
                console.log("获取微信群成员fail: res", res)
                if (res.errcode != 2000) {
                    failTextVantToa("服务器正在修整，请稍后")
                }
                this.mescroll['member'].endErr()
            })
            .catch(res => {
                console.log("获取微信群成员catch：res", res)
                failTextVantToa("服务器正在修整，请稍后")
                this.mescroll['member'].endErr()
            })
            .finally(() => {
                this.$emit('pageBasicDataSeted')
            })
        },
        // 获取需求列表
        getDemandList(page) {
            commonRequestData({
                apiName: `WxGroupUserItem`,
                requestData: {
                    GroupWxId: this.queryStr.wecGroId,
                    KfWxId: this.queryStr.serWecId,
                    flag: 1,
                    Page: page.num,
                    PageSize: page.size,
                }
            })
            .then(res => {
                console.log("获取需求 res：", res)
                if (res.errcode == 0 && res.data && res.data.UsersItem && Array.isArray(res.data.UsersItem) && res.data.UsersItem.length > 0) {
                    if (this.defaultOpt === 'demand') {
                        this.setPageBasicData(res.data)
                    }
                    this.$emit('addList', { // 设置群成员列表数据
                        id: 'demand',
                        list: res.data.UsersItem
                    })
                    this.mesConfig['demand'].total = res.total
                    this.mescroll['demand'].endBySize(res.data.UsersItem.length, res.total)
                } else {
                    if (res.errcode == 1003) {
                        this.$emit('hideDom')
                        return
                    }
                    const list = checkArrIndexObj({
                        arr: this.optList,
                        key: 'id',
                        val: 'demand'
                    }).list
                    this.mescroll['demand'].endErr()
                    if (list.length === 0) {
                        this.mescroll['demand'].showEmpty()
                    }
                }
            }, res => {
                console.log("获取需求 fail: res", res)
                if (res.errcode != 2000) {
                    failTextVantToa("服务器正在修整，请稍后")
                }
                this.mescroll['demand'].endErr()
            })
            .catch(res => {
                console.log("获取需求 catch：res", res)
                failTextVantToa("服务器正在修整，请稍后")
                this.mescroll['demand'].endErr()
            })
            .finally(() => {
                this.$emit('pageBasicDataSeted')
            })
        },
        // 获取互助列表
        getHelpList(page) {
            commonRequestData({
                apiName: `WxGroupUserItem`,
                requestData: {
                    GroupWxId: this.queryStr.wecGroId,
                    KfWxId: this.queryStr.serWecId,
                    flag: 2,
                    Page: page.num,
                    PageSize: page.size,
                }
            })
            .then(res => {
                console.log("获取互助 res：", res)
                if (res.errcode == 0 && res.data && res.data.UsersItem && Array.isArray(res.data.UsersItem) && res.data.UsersItem.length > 0) {
                    if (this.defaultOpt === 'help') {
                        this.setPageBasicData(res.data)
                    }
                    this.$emit('addList', { // 设置群成员列表数据
                        id: 'help',
                        list: res.data.UsersItem
                    })
                    this.mesConfig['help'].total = res.total
                    this.mescroll['help'].endBySize(res.data.UsersItem.length, res.total)
                } else {
                    if (res.errcode == 1003) {
                        this.$emit('hideDom')
                        return
                    }
                    const list = checkArrIndexObj({
                        arr: this.optList,
                        key: 'id',
                        val: 'help'
                    }).list
                    this.mescroll['help'].endErr()
                    if (list.length === 0) {
                        this.mescroll['help'].showEmpty()
                    }
                }
            }, res => {
                console.log("获取互助 fail: res", res)
                if (res.errcode != 2000) {
                    failTextVantToa("服务器正在修整，请稍后")
                }
                this.mescroll['help'].endErr()
            })
            .catch(res => {
                console.log("获取互助 catch：res", res)
                failTextVantToa("服务器正在修整，请稍后")
                this.mescroll['help'].endErr()
            })
            .finally(() => {
                this.$emit('pageBasicDataSeted')
            })
        },
        setPageBasicData(data) {
            this.$emit('setPageBasicData', {
                groupName: data.WxGroupName || '',
                userCount: data.UserCount || 0,
                businessCount: data.BusinessCount || 0,
                updataTime: data.UpdateTime,
                updateMaxCount: data.UpdateCount || 0,
                isBindWechat: data.ThenBindWx || 0,
                demandCount: data.DemandCount || 0,
                partnerCount: data.PartnerCount || 0,
                isSetBus: data.IsBusiness || 0,
                assNo: data.AssNo || 0,
                assType: data.AssType,
                isBeForeUpdataMyInfo: (data.UpdateTime - data.ThenBindWxTime > 0) && (data.UpdateTime - data.BusinessTime > 0) && data.ThenBindWxTime > 0 && data.BusinessTime > 0,
                visitCount: data.ViewPageCount || 0,
            })
        },
        // 设置用户信息左边数据
        setThumbSty({isStick, isBusiness, isRestricted, isBindWx}) {
            const data = {}
            const widthheight = isRestricted ? 47 : 40
            const thumbClassText = this.setThumbClassText(isBusiness, isRestricted, isBindWx, isStick)
            data.width = widthheight
            data.height = widthheight
            data.thumbClass = thumbClassText.class
            data.thumbText = thumbClassText.text
            data.tag = thumbClassText.tag
            return data
        },
        // 设置用户信息左边背景class和文字
        setThumbClassText(isBusiness, isRestricted, isBindWx, isStick) {
            if (isRestricted) {
                return {
                    class: 'stick-limit-head',
                    text: '受限',
                    tag: 'limit',
                }
            }
            if (isStick) {
                return {
                    class: 'stick-user-head',
                    text: '名片',
                    tag: 'stick',
                }
            }
            if (isBindWx && isBusiness) {
                return {
                    class: 'stick-bus-head',
                    text: '名片',
                    tag: 'bus',
                }
            }
            if (isBindWx && isBusiness == 0) {
                return {
                    class: 'stick-index-head',
                    text: '主页',
                    tag: 'index',
                }
            }
            return {
                class: 'stick-empty-head',
                text: '',
                tag: 'empty',
            }
        },
        // 进入业务详情页面
        toUser(userId, tag) {
            if (userId) {
                if (tag === 'bus' || tag === 'stick') {
                    enterUserBus({
                        userId,
                        checkLogin: false,
                    })
                } else if (tag === 'index') {
                    if (process.env.IS_LOCAL === 0) {
                        this.$emit("cachePageData")
                    }
                    enterUserIndex({
                        userId
                    })
                }
            }
        },
        // 更新列表
        updataList() {
            this.$emit('clearActList')
            this.mescroll[this.actOpt].resetUpScroll(true)
        },
        // 获取所有mescroll配置
        getAllMesConfig() {
            const that = this
            const data = {}
            that.optList.forEach((item, index) => {
                const config = that.mescroll[item.id].optUp
                data[item.id] = {}
                // console.log('that.optList[index].list', that.optList[index].list)
                // console.log('that.mesConfig[item.id]', that.mesConfig[item.id])
                data[item.id].optUp = {
                    page: config.page,
                    isUpLoadContinue: that.optList[index].list.length < that.mesConfig[item.id].total && that.mesConfig[item.id].total > 0,
                    id: item.id
                }
            })
            return data
        },
        // 设置所有mescroll up配置
        setAllMesConfig(data) {
            // console.log('setAllMesConfig data', data)
            this.mesCacheConfig = data
        },
    },
    mounted() {
        this.setMescrollList()
    },
    watch: {
        actOpt() {
            for(let i = 0; i < this.optList.length; i++){
                if (this.optList[i].id === this.actOpt) {
                    if (this.optList[i].list.length === 0) {
                        this.mescroll[this.actOpt].triggerUpScroll()
                    }
                    break
                }
            }
        }
    },
    computed: {
        queryStr() {
            return this.query
        },
        optListData() {
            const arr = [].concat(this.optList)
            const that = this
            arr.forEach(item => {
                item.list.forEach(itemList => {
                    itemList.thumbSty = that.setThumbSty({
                        isStick: itemList.fine,
                        isBusiness: itemList.isBusiness,
                        isRestricted: itemList.isRestricted,
                        isBindWx: itemList.isBindWx,
                    })
                    // itemList.supply = `asdasdasdsadasdasdas<p contenteditable="false" style=""><img class="up-img" src="https://www.mroyewubiji.com/Api/GetHttpImg/4d62a38c7f764b71a536c14f498135f5" loading="lazy" style=""></p><div class="stage-div" style="">kl.kl.kl</div><p contenteditable="false" style=""><img class="up-img" src="https://www.mroyewubiji.com/Api/GetHttpImg/8044b2806b4644eca0619b6fc112e04b" loading="lazy" style=""></p><div class="stage-div" style=""><img class="up-img" src="https://www.mroyewubiji.com/Api/GetHttpImg/4d62a38c7f764b71a536c14f498135f5" loading="lazy" style="">sdfsdfsdf</div>`
                    if (itemList.sex == 2) {
                        itemList.sex = 0
                    }
                    itemList.demandText = getText(itemList.demand)
                })
            })
            return arr
        },
        selectListObj() {
            const obj = {}
            this.optList.forEach(item => {
                obj[item.id] = item.list
            })
            return obj
        },
    },
    components: {
        UserHeadImg,
        SexIcon,
        UserInfoOption,
        ImageVant,
    }
}
</script>
                        
<style lang="scss" scoped>
#wechat-member-list-mescroll {
    overflow-y: scroll;

    .list {
        height: 100%;
        width: 100%;
        overflow-y: scroll;

        .list-li {
            padding: 15px;
            &:not(:last-child) {
                border-bottom: 1px solid #eeeeee;
            }

            .list-li-box {
                &:not(:last-child) {
                    margin-bottom: 8px;
                }
            }

            .head {
                display: flex;
                min-height: 70px;
                max-height: 74px;
                width: 100%;
                border-radius: 5px;
                overflow: hidden;

                .thumb {
                    flex-shrink: 0;
                    height: 100%;
                    width: 55px;
                    border-radius: 5px;
                    overflow: hidden;
                    margin-right: 5px;
                    font-size: 12px;

                    .thumb-box {
                        display: flex;
                        height: 100%;
                        width: 100%;
                        flex-direction: column;
                        align-items: center;
                        color: white;
                        padding: 4px;
                        justify-content: space-between;
                    }

                    .stick-user-head {
                        background: #f19800;
                    }

                    .stick-bus-head {
                        background: #00c702;
                    }

                    .stick-index-head {
                        background: #0197dd;
                    }

                    .stick-limit-head {
                        background: #cccccc;
                    }
                }
            }

            .statistics {
                font-size: 12px;
                color: #999999;
                line-height: 20px;
                margin-top: 5px;

                .visit-count-icon {
                    position: relative;
                    top: 3px;
                }
            }

            .content-box {
                width: 100%;
                height: 100%;

                .wechat-name {
                    font-weight: bold;
                }

                .member-name {
                    color: #999999;
                }
                
                .content-box-row {
                    height: 23px;
                    width: 100%;
                    display: -webkit-box;
                    -webkit-box-pack: center;
                    -webkit-box-orient: vertical;
                    box-orient: vertical;
                    overflow: hidden;
                    -webkit-line-clamp: 1;
                    line-clamp: 1;

                    .icon {
                        font-size: 12px;
                        
                        &:not(:last-child) {
                            margin-right: 5px;
                        }
                    }

                    .opt-tag {
                        display: inline-block;
                        padding: 1px 2px;
                        border: 1px solid #333333;
                        border-radius: 3px;
                        color: #333333;
                        font-size: 12px;
                    }

                    .woshop-working {
                        padding: 3px;
                        font-size: 12px;
                        color: white;
                        background: #00C702;
                        border-radius: 3px;
                    }
                }
            }
        }
    }
}
</style>

<style lang="scss">
.mescroll-upwarp {
    padding: 0;

    .is-all-data {
        height: 60px;
        text-align: center;
        line-height: 60px;
        background: #eeeeee;
        color: #999999;
        font-size: 12px;
    }
}

.empty-info {
    img {
        width: 120px !important;
    }
}
</style>